package com.project.frba.bifront.client.view.users;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.Store;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.grid.ColumnConfig;
import com.gwtext.client.widgets.grid.ColumnModel;
import com.gwtext.client.widgets.grid.GridPanel;
import com.gwtext.client.widgets.layout.FitLayout;
import com.project.frba.bifront.client.model.User;
import com.project.frba.bifront.client.rpc.UserServices;
import com.project.frba.bifront.client.rpc.UserServicesAsync;
import com.project.frba.bifront.client.view.MessageWindow;

public class UserList extends Composite {

	private Window mainWindow = new Window();
	
	private GridPanel gridPanel = new GridPanel();
	
	private Button btAdd = new Button("Agregar usuario");
	
	private Button btRemove = new Button("Eliminar");
	
	private Long selectedUser = null;
	
	private RecordDef recordDef = null;
	

	public UserList() {
		mainWindow.setButtons(new Button[]{btAdd, btRemove});
		mainWindow.setLayout(new FitLayout());
		
		
		loadActions();
		
		FieldDef[] fieldDef = new FieldDef[] { 
				new StringFieldDef("id"),
				new StringFieldDef("username"),
				new StringFieldDef("privilege") };
		recordDef = new RecordDef(fieldDef);

		ColumnConfig[] columns = new ColumnConfig[] {
				new ColumnConfig("ID", "id", 50, false, null),
				new ColumnConfig("Nombre de usuario", "username", 160, true, null),
				new ColumnConfig("Privilegio", "privilege", 100, false, null)
			};
		
		ColumnModel columnModel = new ColumnModel(columns);
		
		Store store = new Store(recordDef);
		
		gridPanel.setStore(store);
		gridPanel.setColumnModel(columnModel);
		gridPanel.setFrame(false);  
		gridPanel.setStripeRows(true);  
		gridPanel.setHeight(250);  
		gridPanel.setWidth(325);
		
		getUsers();
		
		mainWindow.setTitle("Listado de usuarios");
		mainWindow.setResizable(false);
		mainWindow.add(gridPanel);
		mainWindow.setWidth(325);
		initWidget(mainWindow);
		mainWindow.show();
	}

	private void loadActions() {
		final UserList me = this;
		btAdd.addListener(new ButtonListenerAdapter(){
			public void onClick(Button button, EventObject e) {
				new UserForm(0L, me);
			}
		});
		
		btRemove.addListener(new ButtonListenerAdapter(){
			public void onClick(Button button, EventObject e) {
				if(selectedUser != null){
					removeUser(selectedUser);
				}
			}
		});
		
		gridPanel.addGridListener(new ListGridListener(){
			public void onDblClick(EventObject e) {
				Record record = gridPanel.getSelectionModel().getSelected();
				selectedUser = new Long(record.getAsString("id"));
				new UserForm(selectedUser, me);
			}
			
			public void onClick(EventObject e) {
				Record record = gridPanel.getSelectionModel().getSelected();
				selectedUser = new Long(record.getAsString("id"));
			}
		});
	}

	private void getUsers() {
		AsyncCallback<List<User>> callback = new AsyncCallback<List<User>>(){
			public void onFailure(Throwable caught) {
				new MessageWindow("No se pudo obtener todos los usuarios.");
			}
			
			public void onSuccess(List<User> users) {
				loadListing(users);
			}
		};
		
		UserServicesAsync userServices = (UserServicesAsync)GWT.create(UserServices.class);
		userServices.getAllUsers(callback);		
	}

	private void loadListing(List<User> users) {
		Store store = gridPanel.getStore();
		store.removeAll();
		for (User user : users) {
			store.add(recordDef.createRecord(user.getId().toString(), new Object[]{
					user.getId().toString(),
					user.getUsername(),
					user.getPrivilege()
					}));
			store.commitChanges();
		}
	}
	
	private void removeUser(Long id){
		AsyncCallback<Boolean> callback = new AsyncCallback<Boolean>(){
			public void onFailure(Throwable caught) {
				new MessageWindow("Error en el servicio.");
			}
			
			public void onSuccess(Boolean result) {
				if(result){
					Record record = gridPanel.getSelectionModel().getSelected();
					Store store = gridPanel.getStore();
					store.remove(record);
					store.commitChanges();
				} else {
					new MessageWindow("Ha ocurrido un error al intentar eliminar el usuario.");
				}
			}
		};
		
		UserServicesAsync userServices = (UserServicesAsync)GWT.create(UserServices.class);
		userServices.removeUser(id, callback);
	}

	public void refreshList() {
		getUsers();
	}
	
	
	

}
